package com.lzh.others.basejava.IO_18;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ProcessFiles {
    public interface Strategy {
        void process(File file);
    }

    private Strategy    strategy;
    private String ext;

    public ProcessFiles(Strategy strategy, String ext) {
        this.strategy = strategy;
        this.ext = ext;
    }

    public void start(String[] args) {
        try {
            if (args.length == 0) {
                processDirectoryTree(new File("."));
            } else {
                for (String arg : args) {
                    File fileArg = new File(arg);
                    if (fileArg.isDirectory()) {
                        processDirectoryTree(fileArg);
                    } else {
                        strategy.process(fileArg.getCanonicalFile());
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void processDirectoryTree(File root) throws IOException {
        String absolutePath = root.getAbsolutePath();
        System.out.println("absolutePath = " + absolutePath);
        String regex = ".*\\." + ext;
        System.out.println("regex = " + regex);
        for (File file : Directory.walk(absolutePath, regex)) {
            strategy.process(file.getCanonicalFile());
        }
    }

    public static void main(String[] args) {
        Class<?> clazz = Directory.class;
        URL resource = clazz.getResource(clazz.getSimpleName() + ".class");
        File path = new File(resource.getPath()).getParentFile();
        String absolutePath = path.getAbsolutePath();
        args = new String[]{absolutePath};
        new ProcessFiles(    new Strategy() {
            @Override
            public void process(File file) {
                System.out.println("file = " + file.getName());
            }
        }, "java").start(args);
    }
}
